package com.hunktimes.wholesale.ui.pages

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.viewModels
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.base.BasePageFragment
import com.hunktimes.wholesale.databinding.FragmentRegisterBinding
import com.hunktimes.wholesale.extension.isHKPhone
import com.hunktimes.wholesale.util.ToastUtil
import com.hunktimes.wholesale.vm.RegistVM
import com.hunktimes.wholesale.widget.CountDown

/**
 * Author: Delete
 * Date: 2020/7/29 10:23
 * Description:
 *
 */
class RegisterFragment : BasePageFragment(R.layout.fragment_register) {
    override val titleRes: Int
        get() = R.string.title_register
    lateinit var viewBinding: FragmentRegisterBinding

    val vm by viewModels<RegistVM>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = FragmentRegisterBinding.bind(view)
    }

    var countDown: CountDown? = null
    override fun onStart() {
        super.onStart()
        viewBinding.phoneEt.doOnTextChanged { text, _, _, _ -> vm.phone.value = text.toString() }
        viewBinding.sendSmsTv.setOnClickListener {
            val phone = vm.phone.value ?: ""
            if (phone.isBlank()) {
                ToastUtil.showErrorToast(getString(R.string.toast_input_phone))
                return@setOnClickListener
            } else if (!phone.isHKPhone()) {
                ToastUtil.showErrorToast(getString(R.string.toast_phone_incorrect))
                return@setOnClickListener
            }
            vm.sendSmsCode()
            countDown = CountDown(requireContext(), it as TextView, 10)
            countDown?.start()
        }
    }

    override fun onDestroy() {
        countDown?.cancelWrap()
        super.onDestroy()
    }
}